#!/usr/bin/env python
"""
##############################################################################
# 用法：./visitor_replace.py rootDir fromStr toStr [-l(list only)]            #
# 在目录树里的所有文件中进行全局搜索并替换：在所有文本文件中将fromStr替换成toStr        #
##############################################################################
"""

import sys
from visitor import SearchVisitor


class ReplaceVisitor(SearchVisitor):
    """
    ##########################################################################
    将startDir及其子目录下所有文件中的fromStr替换成toStr；运行后，修改过变量的文件存储在
    列表obj.changed中。
    ##########################################################################
    """

    def __init__(self, fromStr, toStr, listOnly=False, trace=0):
        self.changed = []
        self.toStr = toStr
        self.listOnly = listOnly
        SearchVisitor.__init__(self, fromStr, trace)

    def visitMatch(self, filePath, text):
        self.changed.append(filePath)
        if not self.listOnly:
            open(filePath, 'w').write(text.replace(self.context, self.toStr))


def main():
    listOnly = '-l' in sys.argv
    visitor = ReplaceVisitor(sys.argv[2], sys.argv[3], listOnly)
    if listOnly or input('是否开始更改？') == 'y':
        visitor.run(sys.argv[1])
        action = '发现的' if listOnly else '更改的'
        print('访问了', visitor.fileCount, '个文件，')
        print(action, '了', len(visitor.changed), '个文件：')
        for changeFilePath in visitor.changed:
            print(changeFilePath)


if __name__ == '__main__':
    main()
